<?php

namespace App\Console\Commands;

use App\Models\Configuration;
use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\FileNotFoundException;

class ConfigurationCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'config:export-seed {classname=ConfigurationSeeder}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '把后台配置导入到seeder';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $name = $this->argument('classname');
            $contents = $this->getStub('ConfigurationSeeder');
            $seedFile = $this->laravel->databasePath('seeders/'.$name.'.php');
            $config = Configuration::query()->select('type', 'key', 'value', 'describe')->orderBy('id')->get()->toArray();
            if (!$config) {
                $this->info('无可备份数据');
                die;
            }
            $contents = str_replace('ArrayConfig',$this->varExport($config, str_repeat(' ', 12)), $contents);
            $this->laravel['files']->put($seedFile, $contents);
            $this->line('<info>Configurations tables seed file was created:</info> '.str_replace(base_path(), '', $seedFile));
            $this->line("Use: <info>php artisan db:seed --class=$name</info>");
        } catch (FileNotFoundException $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * Get stub contents.
     *
     * @param $name
     *
     * @return string
     * @throws FileNotFoundException
     */
    protected function getStub($name): string
    {
        return $this->laravel['files']->get(base_path("stubs/$name.stub"));
    }

    protected function varExport($var, $indent = ''): ?string
    {
        switch (gettype($var)) {

            case 'string':
                return '"'.addcslashes($var, "\\\$\"\r\n\t\v\f").'"';

            case 'array':
                $indexed = array_keys($var) === range(0, count($var) - 1);

                $r = [];

                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        .($indexed ? '' : $this->varExport($key).' => ')
                        .$this->varExport($value, "{$indent}    ");
                }

                return "[\n".implode(",\n", $r)."\n".$indent.']';

            case 'boolean':
                return $var ? 'true' : 'false';

            case 'integer':
            case 'double':
                return $var;

            default:
                return var_export($var, true);
        }
    }
}


